package com.han.service.Impl;


import cn.hutool.core.util.RandomUtil;
import com.han.remote.Service2Client;
import com.han.service.HelloService;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;


@Service
public class HelloServiceImpl implements HelloService {

    private final DiscoveryClient discoveryClient;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private Service2Client service2Client;

    public HelloServiceImpl(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    @Override
    public void sayHi() {
        System.out.println("service-1 say hi");
        System.out.println(service2Client.getHi());
    }


    public void sayHiByRestTemplate() {
        System.out.println("service-1 say hi");

        List<ServiceInstance> instances = discoveryClient.getInstances("service_2");
        // 2.负载均衡，挑选一个实例
        ServiceInstance instance = instances.get(RandomUtil.randomInt(instances.size()));
        // 3.获取实例的IP和端口
        ResponseEntity<String> response = restTemplate.exchange(
                instance.getUri() + "/hi",
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<String>() {
                },
                new Object());
        System.out.println(response.getBody());
        System.out.println(response);
    }
}
